package quiz;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class CreateAccountServlet
 */
@WebServlet("/CreateAccount")
public class CreateAccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateAccountServlet() {
        super();

    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dpatch = request.getRequestDispatcher("create-account.jsp");
		dpatch.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext ctxt = request.getServletContext();
		DataBase db = (DataBase)ctxt.getAttribute("db");
		
		String errorMessage = "";
		
		String name = (String)request.getParameter("name");
		String username = (String)request.getParameter("username");
		String password = (String)request.getParameter("password");
		
		Account acct = db.getAccountByUsername(username);
		if (acct != null) {
			errorMessage += "Username already exists.\n";
		}
		
		/* input validation */
		if (username.length() < 5) errorMessage += "Please choose a username with at least 6 characters.\n";
		if (password.length() < 5) errorMessage += "Please choose a password with at least 6 characters.\n";
		if (name.length() == 0) errorMessage += "Please enter your name.\n";
		
		
		if (errorMessage.length() == 0)	{
			boolean isAdmin = request.getParameter("isAdmin") != null;
			
			acct = new Account(name, username, Account.hashPassword(password), isAdmin);
			db.storeAccount(acct);
			
			int id = acct.getID();
			
			acct = db.getAccount(id);
			
			acct = db.getAccountByUsername(username);
			
			HttpSession session = request.getSession();
			session.setAttribute("account", acct);
			
			response.sendRedirect("Profile");
		}
		else {
			request.setAttribute("error", errorMessage);
			
			RequestDispatcher dpatch = request.getRequestDispatcher("create-account.jsp");
			dpatch.forward(request, response);
		}
		
	}

}
